package com.cqut.forum.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 文件处理公共类
 * @author yangxun
 */
public abstract class FileHandle {
	  /**
	   * 创建缩略图
	   * @param fileName
	   * @return
	   * @throws IOException
	   */
	  public static String createThumbnail(String fileName,double t) throws IOException {
		  File _file = new File(fileName); //读入文件
		  String srcFile = _file.getName();
		  String destFile = _file.getParent()+"\\"+srcFile.substring(0, srcFile.lastIndexOf("."));
		  if(fileName.indexOf(".jpg")>0){
			  destFile = destFile + ".png";
		  }
		  else{
			  destFile = destFile + ".jpg";
		  }
		  Image img = javax.imageio.ImageIO.read(_file); //构造Image对象
		  int width = img.getWidth(null); //得到源图宽
		  int height = img.getHeight(null); //得到源图长
		  
		  resize(img,destFile,(int)(width*t), (int)(height*t));
		  return destFile;
	  }
	  /**
	   * 强制压缩/放大图片到固定的大小
	   * @param w int 新宽度
	   * @param h int 新高度
	   * @throws IOException
	   */
	  private static void resize(Image img,String destFile,int w, int h) throws IOException {
		   BufferedImage _image = new BufferedImage(w, h,
		                                             BufferedImage.TYPE_INT_RGB);
		   _image.getGraphics().drawImage(img, 0, 0, w, h, null); //绘制缩小后的图
		   FileOutputStream out = new FileOutputStream(destFile); //输出到文件流
	   	   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
	   	   encoder.encode(_image); //近JPEG编码
		   out.close();
	  }
	  /**
	   * 按照固定的比例缩放图片
	   * @param t double 比例
	   * @throws IOException
	   */
	  /*public void resize(double t) throws IOException {
	    int w = (int) (width * t);
	    int h = (int) (height * t);
	    resize(w, h);
	  }*/
}
